import React, { useState, useEffect } from 'react';
import { obj_str, cline, uReal, ErrView, Wait, BaseDlg, NuiBt } from 'sui';
import { g_db } from 'db/state';
import { loc } from 'local';
import { get_rgb, split_psn } from 'client/pick/cmd';
import { Scan, Pcode} from '../../sort/ctl/ctl';

const DlgFind = ({ open, setOpen }) => {
    const [fin, setFin] = useState("scan");
    const [err, setErr] = useState("");
    const [value, SetValue] = useState();
    const [wait, setWait] = useState(false);

    useEffect(() => {
        if (!open) {
            return;
        }

        setErr("");
        SetValue(null);

        g_db.stop_scan();
    }, [open]);

    const hfind = (msn) => {
        if (!msn) {
            return;
        }

        setWait(true);

        uReal(null, "pair/find",
            {
                line: cline(),
                tp: "away",
                sn: msn,
            },
            r => {
                SetValue({
                    box_sn: obj_str(r, "box"),
                    msn: msn,
                });
                setErr("");
                setWait(false);
            },
            e => {
                SetValue(null);
                setErr("没有找到");
                setWait(false);
            });
    };

    const getView = () => {
        if (fin === "scan") {
            return <Scan hcmd={hfind} open={open} setOpen={setOpen} lok="搜索"/>;
        }

        return <Pcode hcmd={hfind} open={open} setOpen={setOpen} lok="搜索"/>;
    };

    const getResult = () => {
        if (err) {
            return <ErrView err={err}/>;
        }

        if (!value) {
            return;
        }

        const sn = obj_str(value, "box_sn");
        const cl = get_rgb(sn);

        return (
            <div className="text-2xl mx-4 mb-4">
                <div className="rounded-lg px-4" style={{ background: `rgb(${cl[0]}, ${cl[1]}, ${cl[2]})`, color: `${cl[3]}` }}>
                    箱号<span className="ml-4">{sn}</span>
                </div>
                <div>轴承<span className="ml-4">{split_psn(obj_str(value, "msn"))}</span></div>
            </div>
        );
    };

    return (
        <BaseDlg open={open} title="查找轴承">
            <div className="flex flex-col">
                {getResult()}
                <div className="flex flex-row ml-4">
                    <NuiBt color={fin === "scan" ? "green": "blue"} hcmd={() => setFin("scan")}>{loc("base_62")}</NuiBt>
                    <NuiBt className="ml-4" color={fin === "scan" ? "blue": "green"} hcmd={() => setFin("pass")}>{loc("base_59")}</NuiBt>
                </div>
                {getView()}
                <Wait wait={wait}/>
            </div>
        </BaseDlg>
    );
};

export {DlgFind};
